package com.spring.controller.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.ListUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.spring.domain.Content;
import com.spring.domain.File;
import com.spring.domain.User;
import com.spring.domain.vo.ImgContent;
import com.spring.service.content.IContent;
import com.spring.service.content.IContentType;
import com.spring.service.file.IFile;
import com.spring.service.user.IUser;
import com.utils.Validation;

public class ContentController extends MultiActionController  {
	private static final Logger logger = Logger.getLogger(ContentController.class);
    
	private IContent 		contentService;
	private IContentType 	contentTypeService;
    private IUser 			userService;
    private IFile 			fileService;
    
	private final String ACTION_DELETE_RELATE_USER		=	"deleteRelation";
    private final String ACTION_RELATE_USER 			=	"createRelation";
    
    private final String ACTION_DELETE_RELATE_IMAGE		=	"deleteRelation";
    private final String ACTION_RELATE_IMAGE 			=	"createRelation";
    private final String ACTION_ORDER_IMAGE				=	"updateOrder";
    
    private final String ACTION_DELETE_RELATE_DOCUMENT	=	"deleteRelation";
    private final String ACTION_RELATE_DOCUMENT 		=	"createRelation";
    
    private final String ACTION_DELETE_RELATE_GALLERY	=	"deleteRelation";
    private final String ACTION_RELATE_GALLERY 			=	"createRelation";
    
	private static final String CONTENT_LIST_VIEW 		= 	"content/contentList";
	private static final String NEW_CONTENT_VIEW 		= 	"content/newContent";
	private static final String CONTENT_INDEX_VIEW 		= 	"content/index";
	private static final String MODIFY_CONTENT_VIEW 	= 	"content/modifyContent";
	
	private static final String USER_RELATE_VIEW 		= 	"content/relateUser";
	private static final String IMAGE_RELATE_VIEW 		= 	"content/relateImage";
	private static final String DOCUMENT_RELATE_VIEW 	= 	"content/relateDocument";
	private static final String GALLERY_RELATE_VIEW 	= 	"content/relateGallery";
	
    public ModelAndView contentList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        Map<String,Object> model = new HashMap<String, Object>();        
        logger.info("Creating model");
        model.put("contentTypes", this.contentTypeService.getContentTypes());
        model.put("contents", this.contentService.getContents());
        logger.info("Returning "+CONTENT_LIST_VIEW+" view");

		return new ModelAndView(CONTENT_LIST_VIEW, "model", model);
    }
    
    public ModelAndView manageRelationGallery(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    	List<String> 	messages 		= new ArrayList<String>();
    	List<HashMap> 	errorMessages 	= new ArrayList<HashMap>();
        
    	List<String> 	idSelected 		= Arrays.asList (ServletRequestUtils.getStringParameters(request, "galleryId") );
    	String 			action 			= ServletRequestUtils.getStringParameter	(request, "action"		,"0");
        int 			contentId 		= ServletRequestUtils.getIntParameter		(request, "contentId"	,0);
        
        final int GALLERY_TYPE = 3;
        
        logger.debug("action recuperata:"+action);
        
        if(ACTION_DELETE_RELATE_GALLERY.equalsIgnoreCase(action)){
        	List<Content> galleries = getGalleryList(request);
        	if(!galleries.isEmpty() && contentId!=0){
        		logger.debug("deleting relation with Galleries:"+ galleries.toString()+", contentId:"+ contentId);
				this.contentService.deleteGallerytRelation(galleries, contentId);
        		messages.add("content.deleteUserSucess");
			}else{
				logger.error("Empty contentId or no user selected");
				messages.add("error.parametroMancante");
			}
        }else if(ACTION_RELATE_GALLERY.equalsIgnoreCase(action)){
        	logger.debug("ACTION_RELATE_USER");
        	List<Content> galleries = getGalleryList(request);
        	
        	if(!galleries.isEmpty() && contentId!=0){
        		logger.debug("saving relation with gallery contents :"+ galleries.toString()+", contentId:"+ contentId);
				this.contentService.insertGalleryRelation(galleries, contentId);
        		messages.add("content.relateGallerySucess");
        		
			}else{
				logger.error("Empty contentId or no gallery selected");
				messages.add("error.parametroMancante");
			}
        }
        
        //retrieving updated data for view
        List<Content> relatedGalleries 	= this.contentService.getGalleriesRelated(contentId);
        List<Content> galleries 		= this.contentService.getContentsByType(GALLERY_TYPE);
        List<Content> toRemove 			= getGalleriesToRemove(relatedGalleries, galleries);
        galleries.removeAll(toRemove);
        
        //creating model 
        Map<String,Object> model = new HashMap<String, Object>(); 
        model.put("contentId"		, contentId);
		model.put("relatedGalleries", relatedGalleries);
		model.put("galleries"		, galleries);
        model.put("messages"		, messages);
        model.put("errors"			, errorMessages);
        
        logger.info("Returning "+ GALLERY_RELATE_VIEW +" view");
        return new ModelAndView(GALLERY_RELATE_VIEW, "model", model);
    }
    
    public ModelAndView manageRelationUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    	List<String> 	messages 		= new ArrayList<String>();
    	List<HashMap> 	errorMessages 	= new ArrayList<HashMap>();
        
    	List<String> 	idSelected 		= Arrays.asList (ServletRequestUtils.getStringParameters(request, "userId") );
    	String 			action 			= ServletRequestUtils.getStringParameter	(request, "action"		,"0");
        int 			contentId 		= ServletRequestUtils.getIntParameter		(request, "contentId"	,0);
        
        logger.debug("action recuperata:"+action);
        
        if(ACTION_DELETE_RELATE_USER.equalsIgnoreCase(action)){
        	List<User> users = getUserList(request);
        	if(!users.isEmpty() && contentId!=0){
        		logger.debug("deleting relation with users:"+ users.toString()+", contentId:"+ contentId);
				this.contentService.deleteUserRelation(users, contentId);
        		messages.add("content.deleteUserSucess");
			}else{
				logger.error("Empty contentId or no user selected");
				messages.add("error.parametroMancante");
			}
        }else if(ACTION_RELATE_USER.equalsIgnoreCase(action)){
        	logger.debug("ACTION_RELATE_USER");
        	List<User> users = getUserList(request);
        	
        	if(!users.isEmpty() && contentId!=0){
        		logger.debug("saving relation with users:"+ users.toString()+", contentId:"+ contentId);
				this.contentService.insertUserRelation(users, contentId);
        		messages.add("content.relateUserSucess");
        		
			}else{
				logger.error("Empty contentId or no user selected");
				messages.add("error.parametroMancante");
			}
        }
        
        //retrieving updated data for view
        List<User> usersRelated = this.contentService.getUsersRelated(contentId);
        List<User> users 		= this.userService.getUsers();
        List<User> toRemove 	= getUserToRemove(usersRelated, users);
        users.removeAll(toRemove);
        
        //creating model 
        Map<String,Object> model = new HashMap<String, Object>(); 
        model.put("contentId"	, contentId);
		model.put("relatedUser"	, usersRelated);
		model.put("users"		, users);
        model.put("messages"	, messages);
        model.put("errors"		, errorMessages);
        
        logger.info("Returning "+USER_RELATE_VIEW+" view");
        return new ModelAndView(USER_RELATE_VIEW, "model", model);
    }
    
    
    //ACTION PER RELAZIONARE IMMAGINI AL CONTENT
    public ModelAndView manageRelationImage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    	List<String> 	messages 		= new ArrayList<String>();
    	List<HashMap> 	errorMessages 	= new ArrayList<HashMap>();
        
    	List<String> 	idSelected 		= Arrays.asList (ServletRequestUtils.getStringParameters(request, "userId") );
    	String 			action 			= ServletRequestUtils.getStringParameter	(request, "action"		,"0");
        int 			contentId 		= ServletRequestUtils.getIntParameter		(request, "contentId"	,0);
        int 			maxNumberImg 	= ServletRequestUtils.getIntParameter		(request, "maxNumberImg"	,0);
        
        List<ImgContent> relatedFiles = this.contentService.getImgRelated(contentId);
        
        logger.debug("action recuperata:"+action);
        
        if(ACTION_DELETE_RELATE_IMAGE.equalsIgnoreCase(action)){
        	List<File> files = getFileList(request);
        	if(!files.isEmpty() && contentId!=0){
        		
        		logger.debug("deleting relation with files:"+ files.toString()+", contentId:"+ contentId);
				this.contentService.deleteImageRelation(files, contentId);
        		messages.add("content.deleteImgRelationSucess");
        		
			}else{
				logger.error("Empty contentId or no user selected");
				messages.add("error.parametroMancante");
			}
        }else if(ACTION_RELATE_IMAGE.equalsIgnoreCase(action)){
        	logger.debug("ACTION_RELATE_IMAGE");
        	List<File> files = getFileList(request);
        	
        	if(!files.isEmpty() && contentId!=0){
        		if( files.size() <= maxNumberImg && relatedFiles.size()+files.size() <= maxNumberImg ){
	        		logger.debug("saving relation with content:"+ contentId + ", files:"+files.toString());
					this.contentService.insertImgRelation(files, contentId);
	        		messages.add("content.relateImgSucess");
        		}else{
        			logger.error("Il contenuto non permette questo numero di files");
    				messages.add("error.maxNumberFilesRelatedReached");
        		}
			}else{
				logger.error("Empty contentId or no user selected");
				messages.add("error.parametroMancante");
			}
        }else if(ACTION_ORDER_IMAGE.equalsIgnoreCase(action)){
        	logger.debug("ACTION_ORDER_IMAGE");
        	List<File> files = getFileList(request);
        	
        	if(!files.isEmpty() && contentId!=0){
        		for (Iterator iterator = files.iterator(); iterator.hasNext();) {
					File file = (File) iterator.next();
					int position = ServletRequestUtils.getIntParameter(request, "order"+file.getId(),0);
					if(position!=0){
						this.contentService.updatePositionImgRelation(file, contentId, position);
						messages.add("content.updatePositionForImgRelatedSucess");
					}
				}
        	}else{
				logger.error("Empty contentId or no user selected");
				messages.add("error.parametroMancante");
			}
        }
        
        //retrieving updated data for view
        List<ImgContent> files 		= this.contentService.getImg();
        relatedFiles 				= this.contentService.getImgRelated(contentId);
        List<ImgContent> toReturn 	= getImgNotRelated(relatedFiles, files);
    
        //creating model 
        Map<String,Object> model = new HashMap<String, Object>(); 
        model.put("contentId"	, contentId);
        model.put("maxNumberImg", maxNumberImg);
		model.put("relatedFiles", relatedFiles);
		model.put("files"		, toReturn);
        model.put("messages"	, messages);
        model.put("errors"		, errorMessages);
        
        logger.info("Returning "+IMAGE_RELATE_VIEW+" view");
        return new ModelAndView(IMAGE_RELATE_VIEW, "model", model);
    }
    
    //ACTION PER RELAZIONARE DOCUMENTI AL CONTENT
    public ModelAndView manageRelationDocument(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    	List<String> 	messages 		= new ArrayList<String>();
    	List<HashMap> 	errorMessages 	= new ArrayList<HashMap>();
        
    	List<String> 	idSelected 		= Arrays.asList (ServletRequestUtils.getStringParameters(request, "userId") );
    	String 			action 			= ServletRequestUtils.getStringParameter	(request, "action"		,"0");
        int 			contentId 		= ServletRequestUtils.getIntParameter		(request, "contentId"	,0);
        
        List<File> relatedFiles = this.contentService.getFileRelated(contentId);
        
        logger.debug("action recuperata:"+action);
        
        if(ACTION_DELETE_RELATE_DOCUMENT.equalsIgnoreCase(action)){
        	logger.debug("ACTION_DELETE_RELATE_DOCUMENT");
        	List<File> files = getFileList(request);
        	if(!files.isEmpty() && contentId!=0){
        		logger.debug("deleting relation with files:"+ files.toString()+", contentId:"+ contentId);
				this.contentService.deleteDocumentRelation(files, contentId);
        		messages.add("content.deleteDocumentRelationSucess");
			}else{
				logger.error("Empty contentId or no user selected");
				messages.add("error.parametroMancante");
			}
        }else if(ACTION_RELATE_DOCUMENT.equalsIgnoreCase(action)){
        	logger.debug("ACTION_RELATE_DOCUMENT");
        	List<File> files = getFileList(request);
        	
        	if(!files.isEmpty() && contentId!=0){
	        		logger.debug("saving relation with content:"+ contentId + ", files:"+files.toString());
					this.contentService.insertDocumentRelation(files, contentId);
	        		messages.add("content.relateDocumentSucess");
			}else{
				logger.error("Empty contentId or no user selected");
				messages.add("error.parametroMancante");
			}
        }
        
        //retrieving updated data for view
        List<File> files 			= this.contentService.getFile();
        relatedFiles 				= this.contentService.getFileRelated(contentId);
        List<File> toReturn 		= getFileNotRelated(relatedFiles, files);
    
        //creating model 
        Map<String,Object> model = new HashMap<String, Object>(); 
        model.put("contentId"	, contentId);
		model.put("relatedFiles", relatedFiles);
		model.put("files"		, toReturn);
        model.put("messages"	, messages);
        model.put("errors"		, errorMessages);
        
        logger.info("Returning "+DOCUMENT_RELATE_VIEW+" view");
        return new ModelAndView(DOCUMENT_RELATE_VIEW, "model", model);
    }

	private List<User> getUserList(HttpServletRequest request) {
		List<String> userIds = request.getParameterValues("userId") == null ? ListUtils.EMPTY_LIST : Arrays.asList(request.getParameterValues("userId")) ;
		List<User> users = new ArrayList<User>();
		for (Iterator<String> iterator = userIds.iterator(); iterator.hasNext();) {
			final String string = iterator.next();
			users.add(new User(){{
				setId(Integer.valueOf(string).intValue());
				}}
			);
		}
		return users;
	}
	
	private List<Content> getGalleryList(HttpServletRequest request) {
		List<String> galleryIds = request.getParameterValues("galleryId") == null ? ListUtils.EMPTY_LIST : Arrays.asList(request.getParameterValues("galleryId")) ;
		List<Content> contents = new ArrayList<Content>();
		for (Iterator<String> iterator = galleryIds.iterator(); iterator.hasNext();) {
			final String string = iterator.next();
			contents.add(new Content(){{
				setId(Integer.valueOf(string).intValue());
				}}
			);
		}
		return contents;
	}
	
	private List<File> getFileList(HttpServletRequest request) {
		List<String> userIds = request.getParameterValues("fileId") == null ? ListUtils.EMPTY_LIST : Arrays.asList(request.getParameterValues("fileId")) ;
		List<File> users = new ArrayList<File>();
		for (Iterator<String> iterator = userIds.iterator(); iterator.hasNext();) {
			final String string = iterator.next();
			users.add(new File(){{
				setId(Integer.valueOf(string).intValue());
				}}
			);
		}
		return users;
	}
	
    public ModelAndView newContent(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<HashMap> 		errorMessages 	= new ArrayList<HashMap>();
        List<String> 		messages 		= new ArrayList<String>();
        Map<String,Object> 	model 			= new HashMap<String, Object>();   
        
        Content contentDataForm = getNewContentForm(request);
        
        if (validateNewContentDataForm(contentDataForm, errorMessages)){
        	logger.info("Inserting content [\n" + contentDataForm.toString()+"]");
        	
        	int idContentInserted = contentService.insert(contentDataForm);
        	messages.add("ok.insertedContent");
        	model.put("messages", messages);
        	logger.info("Content Inserted with id:"+idContentInserted);
        }else{
        	logger.info("Form Validation Error");
        	model.put("errors", errorMessages);
        	model.put("content", contentDataForm);
        }
        
        model.put("contentTypes", this.contentTypeService.getContentTypes());
        model.put("contentSkins", this.contentTypeService.getContentSkins());
        
        
        logger.info("Returning view:["+NEW_CONTENT_VIEW+"]");
        return new ModelAndView(NEW_CONTENT_VIEW, "model", model);
    }
    
    public ModelAndView modifyContent(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<HashMap> 		errorMessages 	= new ArrayList<HashMap>();
        List<String> 		messages 		= new ArrayList<String>();
        Map<String,Object> 	model 			= new HashMap<String, Object>();   
        
        Content contentDataForm = getNewContentForm(request);
        
        if (validateNewContentDataForm(contentDataForm, errorMessages)){
        	logger.info("Modifying content [\n" + contentDataForm.toString()+"]");
        	contentService.update(contentDataForm);
        	messages.add("ok.modifiedContent");
        	model.put("messages", messages);
        	logger.info("Content Modified with id:"+contentDataForm.toString());
        }else{
        	logger.info("Form Validation Error");
        	model.put("errors", errorMessages);
        	model.put("content", contentDataForm);
        }
        model.put("contentSkins", this.contentTypeService.getContentSkins());
        model.put("contentTypes", this.contentTypeService.getContentTypes());
        
        logger.info("Returning view:["+MODIFY_CONTENT_VIEW+"]");
        return new ModelAndView(MODIFY_CONTENT_VIEW, "model", model);
    }
    
    public ModelAndView deleteContent(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<HashMap> 		errorMessages 	= new ArrayList<HashMap>();
        List<String> 		messages 		= new ArrayList<String>();
        Map<String,Object> 	model 			= new HashMap<String, Object>();   
        
        final int idContent = ServletRequestUtils.getIntParameter(request, "id", 0);
        
       	contentService.delete(new ArrayList<Content>(){{
       		add(new Content(){{
       			setId(idContent);
       		}});
       	}});
        	
       	messages.add("ok.deletedContent");
     
        model.put("contentTypes", this.contentTypeService.getContentTypes());
        model.put("contents", this.contentService.getContents());
       	model.put("messages", messages);
            
       	logger.info("Returning "+CONTENT_LIST_VIEW+" view");
		return new ModelAndView(CONTENT_LIST_VIEW, "model", model);
    }
    
    
    /**
     * 	VALIDAZIONE FORM INSERIMENTO
     * */
    private boolean validateNewContentDataForm(Content contentForm, List<HashMap> error) {
    
    	Content content = (Content) contentForm;
    	
    	if( !StringUtils.hasText( content.getTitolo() ) ){
    		final String field = getApplicationContext().getMessage("text.titolo", 
					new Object[] { "titolo" }, Locale.getDefault());
					
    		error.add(new HashMap<String,String>(){
				private static final long serialVersionUID = 1L;
			{
    			put("key","validation.notEmptyAllowed");
    			put("param1",field);
    		}});
    	}
    	
    	if( !StringUtils.hasText( content.getDescrizione())   ){
    		
    		final String field = getApplicationContext().getMessage("text.descrizione", 
					new Object[] { "descrizione" }, Locale.getDefault());
					
    		error.add(
    			new HashMap<String,String>(){
    				private static final long serialVersionUID = 1L;
    				{
    					put("key","validation.notEmptyAllowed");
    					put("param1",field);
    				}
    			}
    		);
    	}
    	
    	if(error.isEmpty()) return true;
    	
    	return false;
	}
    
    
    
    /**
     * 	RECUPERO OGGETTO CONTENT DA REQUEST PER INSERIMENTO UTENTE
     * */
	private Content getNewContentForm(HttpServletRequest req){
		
    	final String   	id				= ServletRequestUtils.getStringParameter(req, "id"			,"0");
    	final String 	titolo			= ServletRequestUtils.getStringParameter(req, "titolo"		,"");
    	final String 	strillo			= ServletRequestUtils.getStringParameter(req, "strillo"		,"");
    	final String	descrizione 	= ServletRequestUtils.getStringParameter(req, "descrizione"	,"");
    	final String	startDate   	= ServletRequestUtils.getStringParameter(req, "startDate"	,"");
    	
    	final String 	endDate			= ServletRequestUtils.getStringParameter(req, "endDate"		,"");
    	final int		fk_tipo_cont 	= ServletRequestUtils.getIntParameter(req, "fk_tipo_cont"	,1);
    	final int		fk_tipo_skin 	= ServletRequestUtils.getIntParameter(req, "fk_tipo_skin"	,0);
    	final String	insDate   		= ServletRequestUtils.getStringParameter(req, "insDate"		,"");
    	
    	final String 	hasPrivate		= ServletRequestUtils.getStringParameter(req, "hasPrivate"	,"");
    	final String	hasGallery 		= ServletRequestUtils.getStringParameter(req, "hasGallery"	,"");
    	final String	hasFile   		= ServletRequestUtils.getStringParameter(req, "hasDoc"		,"");
    	final String	hasImg   		= ServletRequestUtils.getStringParameter(req, "hasImg"		,"");
    
    	final int 	ihasPrivate		= StringUtils.hasText(hasPrivate) ? 1 : 0;
    	final int	ihasGallery 	= StringUtils.hasText(hasGallery) ? 1 : 0;
    	final int	ihasFile   		= StringUtils.hasText(hasFile) ? 1 : 0;
    	final int	ihasImg   		= StringUtils.hasText(hasImg) ? 1 : 0;
    	
    	return new Content(){{
    		setId(Integer.valueOf(id));
    		setTitolo(titolo);
    		setStrillo(strillo);
    		setDescrizione(descrizione);
    		setStartDate(Validation.getDate(startDate,true));
    		setEndDate(Validation.getDate(endDate,false));
    		setFk_tipo_cont(fk_tipo_cont);
    		setFk_tipo_skin(fk_tipo_skin);
    		setInsDate(Validation.getDate(insDate,true));
    		setHasPrivate(ihasPrivate);
    		setHasGallery(ihasGallery);
    		setHasFile(ihasFile);
    		setHasImg(ihasImg);
    	}};
    }
    
	 /**
     * 	REDIREZIONI A JSP
     * */
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    		return new ModelAndView(CONTENT_INDEX_VIEW);
    }
    
    /*public ModelAndView siteIndex(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	if(checkAdminLogged(request)){
    		return new ModelAndView("index");
    	}else{
    		return new ModelAndView(LOGIN_PAGE_VIEW);
    	}
    }*/
    
    public ModelAndView newContentPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info("Creating model");
        Map<String,Object> model = new HashMap<String, Object>();        
        model.put("contentTypes", this.contentTypeService.getContentTypes());
        model.put("contentSkins", this.contentTypeService.getContentSkins());
        return new ModelAndView(NEW_CONTENT_VIEW,"model",model);
    }
    
    public ModelAndView modifyContentPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info("Creating model");
        int idContent = ServletRequestUtils.getIntParameter(request, "id", 0);
        Map<String,Object> model = new HashMap<String, Object>();        
        model.put("contentTypes", this.contentTypeService.getContentTypes());
        model.put("contentSkins", this.contentTypeService.getContentSkins());
        model.put("content", this.contentService.getContentById(idContent));
        return new ModelAndView(MODIFY_CONTENT_VIEW,"model",model);
    }
    
  

    private List<ImgContent> getImgNotRelated(List<ImgContent> filesRelated, List<ImgContent> files) {
		List<ImgContent> toReturn = new ArrayList<ImgContent>(files);
		
        for (Iterator<ImgContent> iterator = filesRelated.iterator(); iterator.hasNext();) {
        	
        	ImgContent imgContentRelated =  iterator.next();
        	
			for (Iterator<ImgContent> iterator2 = files.iterator(); iterator2.hasNext();) {
				ImgContent imgContent = iterator2.next();
				
				if(imgContent.getFile().getId()==imgContentRelated.getFile().getId()){
					logger.info("found fileRelated > removing Items from fileList");
					toReturn.remove(imgContent);
				}
			}
		}
		return toReturn;
	}
    
	private List<User> getUserToRemove(List<User> usersRelated, List<User> users) {
		List<User> toRemove = new ArrayList<User>();
        for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
			User user =  iterator.next();
			for (Iterator<User> iterator2 = usersRelated.iterator(); iterator2.hasNext();) {
				User userRelated = iterator2.next();
				
				if(userRelated.getId()==user.getId()){
					logger.info("found userRelated > removing Items from userList");
					toRemove.add(user);
				}
			}
		}
		return toRemove;
	}
	
	private List<Content> getGalleriesToRemove(List<Content> galleriesRelated, List<Content> galleries) {
		List<Content> toRemove = new ArrayList<Content>();
        for (Iterator<Content> iterator = galleries.iterator(); iterator.hasNext();) {
        	Content content =  iterator.next();
			for (Iterator<Content> iterator2 = galleriesRelated.iterator(); iterator2.hasNext();) {
				Content contentRelated = iterator2.next();
				
				if(contentRelated.getId()==content.getId()){
					logger.info("found gallery Related > removing Items from galleriesList");
					toRemove.add(content);
				}
			}
		}
		return toRemove;
	}
	
	private List<File> getFileNotRelated(List<File> filesRelated, List<File> files) {
			List<File> toReturn = new ArrayList<File>(files);
			
	        for (Iterator<File> iterator = filesRelated.iterator(); iterator.hasNext();) {
	        	
	        	File fileRelated =  iterator.next();
	        	
				for (Iterator<File> iterator2 = files.iterator(); iterator2.hasNext();) {
					File file = iterator2.next();
					
					if(file.getId()==fileRelated.getId()){
						logger.info("found fileRelated > removing Items from fileList");
						toReturn.remove(file);
					}
				}
			}
			return toReturn;
		}
    
    /**
     * SETTER E GETTER
     * */
	public IContent getContentService() {
		return contentService;
	}

	public void setContentService(IContent contentService) {
		this.contentService = contentService;
	}

	public IContentType getContentTypeService() {
		return contentTypeService;
	}

	public void setContentTypeService(IContentType contentTypeService) {
		this.contentTypeService = contentTypeService;
	}

	public IUser getUserService() {
		return userService;
	}

	public void setUserService(IUser userService) {
		this.userService = userService;
	}

	public IFile getFileService() {
		return fileService;
	}

	public void setFileService(IFile fileService) {
		this.fileService = fileService;
	}

}
